<template>
  <div class="price-chart">
    <div
      v-if="!chartData.length"
      style="
        width: 100%;
        height: 600px;
        display: flex;
        justify-content: center;
        align-items: center;
      "
    >
      <a-empty style="opacity: 0.5" />
    </div>
    <div v-else>
      <!-- <div class="subTitle">{{ date }} 预测收入：{{ pedictIncome }}元</div> -->
      <div
        id="priceChart"
        style="width: 100%; height: 600px"
        v-if="chartData.length"
        key="priceChart"
      ></div>
    </div>
    <!-- <a-empty v-if="!chartData.length" style="opacity: 0.5; margin-top: 50px" /> -->
  </div>
</template>

<script setup>
// 
import * as echarts from "echarts"
import { chartOption } from "./priceChartOption"
import { cloneDeep } from "lodash-es"

const props = defineProps({
  data: {
    type: Array,
    default: () => [],
  },
  date: {
    type: String,
    default: "",
  },
  pedictIncome: {
    type: String,
    default: "",
  },
})

const chartData = ref([])

watch(
  () => props.data,
  async (val) => {
    chartData.value = val

    if (val.length) {
      await nextTick()
      initChart()
    }
  },
  { immediate: true }
)
let resizeHandler = null
const initChart = async () => {
  await nextTick()
  const chartEl = document.getElementById("priceChart")
  if (!chartEl) return

  const chart = echarts.init(chartEl)
  const option = cloneDeep(chartOption)

  // 设置x轴数据
  option.xAxis.data = chartData.value.map((item) => item.time)

  // 设置y轴数据
  option.series[0].data = chartData.value.map((item) => item.price)
  //option.series[0].data = handleLine(chartData.value, "priceHourList")
  chart.setOption(option, true)
  // 监听窗口变化，重绘图表
  resizeHandler = () => {
    chart && chart.resize()
  }
  window.addEventListener("resize", resizeHandler)

  // 组件卸载时移除事件监听
  onUnmounted(() => {
    window.removeEventListener("resize", resizeHandler)
    chart && chart.dispose()
  })
}
const handleLine = (list = [], handleArr) => {
  let newArr = list.reduce((all, item) => {
    return [...all, ...item[handleArr]]
  }, [])

  return newArr
}
</script>

<style lang="less" scoped>
.price-chart {
  width: 100%;
  height: 600px;
  box-sizing: border-box;
  position: relative;
  .subTitle {
    position: absolute;
    top: 60px;
    right: 30px;
    font-size: 14px;
    font-weight: 500;
    color: #999;
  }
}
</style>
